package com.mcbbs.web.util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.stream.IntStream;

public class SHA256 {
    private MessageDigest instance;

    /**
     *     * 利用java原生的类实现SHA256加密
     *     * @param str 加密后的报文
     *     * @return
     *     
     */
    public static String getSHA256(String str) {
        MessageDigest messageDigest;
        String encodestr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodestr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodestr;
    }
    public static boolean isequalsPwd(String password,String hashPassWord){
        if(hashPassWord!=null&&password!=null){
//            将数据库中取出的密码进行字符串分割成数组
            String[] temps = hashPassWord.split("\\$");
//           1.将用户的密码进行加密2.将加密后的密码拼接盐值在进行加密，最后得到最终值
            String mathPwd = getSHA256(getSHA256(password)+temps[2]);
            if(mathPwd.equals(temps[3])){
                return true;
            }
        }
        return false;
    }

//    生成随机盐值(生成的长度)
    public static String getRandomSalt(int length){
        Random random  = new Random();
//        可生成的字符
        String chars = "0123456789abcdefghijklmnopqrstuvwxyz";
        StringBuffer sb = new StringBuffer();
        int charsLength = chars.length();
        for (int i = 0; i <length ; i++) {
            Integer index = random.nextInt(charsLength);
            sb.append(chars.charAt(index));
        }
        return sb.toString();
    }
//    加密密码
    public static String hashPwd(String password){
        if(password!=null){
            String sha256Pwd = getSHA256(password);
            String salt = getRandomSalt(16);
            return "$SHA$"+salt+"$"+(getSHA256(sha256Pwd+salt));
        }
        return null;
    }



    private static String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
    public static String hash(String message, MessageDigest algorithm) {
        algorithm.reset();
        algorithm.update(message.getBytes());
        byte[] digest = algorithm.digest();
        return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
    }
}
